/**
* All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
*
* SdProjectTeamService
* SD项目任命-项目组成员
*
* 修改纪录
* 2021-12-08 版本：1.0 wangxinhua 创建。
* @version 版本：1.0
* @author 作者：wangxinhua
* 创建日期：2021-12-08
*/
package com.topscomm.gpm.service.impl;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.mis.constant.MisSystemConst;
import com.topscomm.mis.mobile.message.service.SendMessageService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.gpm.GpmSystemConst;
import com.topscomm.gpm.pojo.GpmProjectEntity;
import com.topscomm.gpm.pojo.GpmProjectTeamEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.gpm.service.IGpmProjectTeamService;
import com.topscomm.gpm.service.impl.auto.GpmProjectTeamServiceAuto;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service(value = "gpmProjectTeamService")
@Scope(value = "singleton")
public class GpmProjectTeamService extends GpmProjectTeamServiceAuto implements IGpmProjectTeamService {
    @Autowired
    private ICboMessageAppService cboMessageAppService;
    @Autowired
    private ICboMessageSysService cboMessageSysService;
    @Autowired
    private GpmProjectService gpmProjectService;
    @Autowired
    private GpmProjectSuperviseService gpmProjectSuperviseService;
    @Autowired
    private SendMessageService sendMessageService;

    /**
     * @Title: beforeInsert
     * @description:
     * @param entity
     * @author: lanjianwei
     * @date: 2021年1月11日下午4:16:37
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity) {
        super.beforeInsert(entity);
        GpmProjectTeamEntity gpmProjectTeamEntity = (GpmProjectTeamEntity) entity;
        String userCode = gpmProjectTeamEntity.getUsercode();
        String appointmentType= gpmProjectTeamEntity.getAppointmenttype();
        String workGroup = gpmProjectTeamEntity.getWorkgroup();
        String projectRole = gpmProjectTeamEntity.getProjectrole();
        String appointmentId = ConvertUtil.convertToString(gpmProjectTeamEntity.getAppointmentid());
        StringBufferProxy whereSql = new StringBufferProxy();
        whereSql.appendLineSingle("appointmentid = '{0}' and enabled = 1", appointmentId);
        List<GpmProjectTeamEntity> sdProjectTeamEntities = this.queryByWhere(whereSql.toString());
        for (GpmProjectTeamEntity gpmProjectTeamEntity2 : sdProjectTeamEntities) {
            //工号、任命类型、工作组不能同时重复
            if (userCode.equals(gpmProjectTeamEntity2.getUsercode())
                    && workGroup.equals(gpmProjectTeamEntity2.getWorkgroup())
                    && appointmentType.equals(gpmProjectTeamEntity2.getAppointmenttype())) {
                throw new ServiceException("项目组成员重复，请确认后再添加！");
            }
            // 一个工作组中不允许有多个组长
            if (GpmSystemConst.WorkGroupRoleCode.groupLeader.equals(projectRole)
                    && workGroup.equals(gpmProjectTeamEntity2.getWorkgroup())
                    && appointmentType.equals(gpmProjectTeamEntity2.getAppointmenttype())
                    && projectRole.equals(gpmProjectTeamEntity2.getProjectrole())) {
                throw new ServiceException("项目组中只能有一个组长！");
            }
        }
    }

    @Override
    @Transactional
    public List<GpmProjectTeamEntity> queryByAppointmentId(String appointmentId) {
        if (StringUtil.isEmpty(appointmentId)) {
            return new ArrayList<>();
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(GpmProjectTeamEntity.FieldAppointmentid + " =  {0} ", appointmentId);
        return this.queryByWhere(sql.toString());
    }

    public List<Map<String, Object>> queryTeamAndTeamType(String appointmentId) {
        if (StringUtil.isEmpty(appointmentId)) {
            return new ArrayList<>();
        }
        Map<String, Object> param = new HashMap<>();
        param.put("appointmentId", appointmentId);
        return this.queryMap(param, "selectTeamAndTeamType");

    }
    /**
     * @author
     * @date
     * @description: 给项目组成员发送消息
     * @modify:
     */
    @Transactional
    public void sendMessageToGroupMember(String sqlWhere, String sourceid, String sourcetype, String contentInfo) throws Exception{
        // 查询项目和项目组成员
        GpmProjectEntity gpmProjectEntity = gpmProjectService.queryByWhere(sqlWhere).get(0);
        if("1".equals(gpmProjectEntity.getWhetherhistorydata())) {
            return;
        }
        long sdId = gpmProjectEntity.getId();
        List<GpmProjectTeamEntity> sdProjectTeamEntities = this.queryByWhere(sqlWhere);
        // 得到项目组成员code，然后对项目组成员去重
        List<String> userCodeList = sdProjectTeamEntities.stream().map(GpmProjectTeamEntity::getUsercode).distinct().collect(Collectors.toList());
        Map<String, List<GpmProjectTeamEntity>> sdProjectTeamEntityMap = sdProjectTeamEntities.
                stream().collect(Collectors.groupingBy(GpmProjectTeamEntity::getUsercode));
        // 消息内容和标题
        String title = "通用管理项目" + contentInfo + "通知";
        String content = "【" + gpmProjectEntity.getProjectname() + "】" + contentInfo + "变更审核已通过，请知悉";
        // 给项目组成员发送消息
        List<Map<String,Object>> insetListApp = new ArrayList<>();
        List<Map<String,Object>> insetListSys = new ArrayList<>();
        for (String userCode : userCodeList) {
            String userName = sdProjectTeamEntityMap.get(userCode).get(0).getUsername();
            // 系统消息
            Map<String, Object> sysMessageMap = gpmProjectSuperviseService.insertMessageSys(userCode, userName, title,
                    content, sdId, sourcetype);
            sysMessageMap.put("messagetype", MisSystemConst.MobileMessageType.OTHER_TYPE);
            // app消息
            Map<String, Object> appMessageMap = gpmProjectSuperviseService.insertMessageAppForMsg(userCode, userName, title,
                    content, sdId, sourcetype, 0);
            appMessageMap.put("messagetype", MisSystemConst.MobileMessageType.OTHER_TYPE);
            insetListApp.add(appMessageMap);
            insetListSys.add(sysMessageMap);
        }
        if(insetListApp.size()>0) {
//            cboMessageAppService.insertList(insetListApp);
//            cboMessageSysService.insertList(insetListSys);
            sendMessageService.sendSysMessage(insetListSys);
            sendMessageService.sendAppMessage(insetListApp);
        }
    }

    /**
     * @author:zhangjunyao
     * @date:2921-11-12
     * @description: 给C、D级项目组成员发送App消息
     * @modify:
     */
    @Transactional
    public void sendAppMessageToGroupMember(String sqlWhere, String sourceid, String sourcetype) throws Exception {
        // 查询项目和项目组成员
        List<GpmProjectEntity> sdProjectEntities = gpmProjectService.queryByWhere(sqlWhere);
        if(sdProjectEntities.size() == 0) {
            return;
        }
        GpmProjectEntity gpmProjectEntity = sdProjectEntities.get(0);
        List<GpmProjectTeamEntity> sdProjectTeamEntities = this.queryByWhere(sqlWhere);
        // 得到项目组成员code，然后对项目组成员去重
        List<String> userCodeList = sdProjectTeamEntities.stream().map(GpmProjectTeamEntity::getUsercode).distinct().collect(Collectors.toList());
        Map<String, List<GpmProjectTeamEntity>> sdProjectTeamEntityMap = sdProjectTeamEntities.
                stream().collect(Collectors.groupingBy(GpmProjectTeamEntity::getUsercode));
        // 消息内容和标题
        String title = "通用项目任命通知";
        String content = "【" + gpmProjectEntity.getProjectname() + "项目】" + "您被任命为“" + gpmProjectEntity.getProjectname() +
                "项目”工作组成员。请登录通用项目管理系统查阅项目信息。";
        // 给项目组成员发送消息
        List<Map<String,Object>> insetListApp = new ArrayList<>();
        List<Map<String,Object>> insetListSys = new ArrayList<>();
        for (String userCode : userCodeList) {
            // App消息
            String userName = sdProjectTeamEntityMap.get(userCode).get(0).getUsername();
            Map<String, Object> appMessageMap = gpmProjectSuperviseService.insertMessageAppForMsg(userCode, userName, title,
                    content, ConvertUtil.convertToLong(sourceid), sourcetype, 0);
            appMessageMap.put("messagetype", MisSystemConst.MobileMessageType.OTHER_TYPE);
            Map<String, Object> sysMessageMap = gpmProjectSuperviseService.insertMessageSys(userCode, userName, title,
                    content, ConvertUtil.convertToLong(sourceid), sourcetype);
            sysMessageMap.put("messagetype", MisSystemConst.MobileMessageType.OTHER_TYPE);
            insetListApp.add(appMessageMap);
            insetListSys.add(sysMessageMap);
        }
        if(insetListApp.size()>0) {
//            cboMessageAppService.insertList(insetListApp);
//            cboMessageSysService.insertList(insetListSys);
            sendMessageService.sendSysMessage(insetListSys);
            sendMessageService.sendAppMessage(insetListApp);
        }
    }
    /**
     * @Title: updateBefore
     * @description:
     * @param map
     * @author: houyuhang
     * @date: 2021年1月11日下午4:16:37
     * @modify:
     */
    @Override
    protected void updateBefore(Map<String, Object> map) {
        super.updateBefore(map);
        GpmProjectTeamEntity gpmProjectTeamEntity = new GpmProjectTeamEntity();
        gpmProjectTeamEntity.convertFromMap(map);
        String userCode = gpmProjectTeamEntity.getUsercode();
        String appointmentType= gpmProjectTeamEntity.getAppointmenttype();
        String workGroup = gpmProjectTeamEntity.getWorkgroup();
        String projectRole = gpmProjectTeamEntity.getProjectrole();
        String appointmentId = ConvertUtil.convertToString(gpmProjectTeamEntity.getAppointmentid());
        String id = ConvertUtil.convertToString(gpmProjectTeamEntity.getId());
        StringBufferProxy whereSql = new StringBufferProxy();
        whereSql.appendLineSingle("appointmentid = '{0}' and enabled = 1", appointmentId);
        List<GpmProjectTeamEntity> sdProjectTeamEntities = this.queryByWhere(whereSql.toString());
        for (GpmProjectTeamEntity gpmProjectTeamEntity2 : sdProjectTeamEntities) {
            //工号、任命类型、工作组不能同时重复
            if (userCode.equals(gpmProjectTeamEntity2.getUsercode())
                    && workGroup.equals(gpmProjectTeamEntity2.getWorkgroup())
                    && appointmentType.equals(gpmProjectTeamEntity2.getAppointmenttype())
                    && !id.equals(ConvertUtil.convertToString(gpmProjectTeamEntity2.getId()))) {
                throw new ServiceException("项目组成员重复，请确认后再添加！");
            }
            // 一个工作组中不允许有多个组长
            if (GpmSystemConst.WorkGroupRoleCode.groupLeader.equals(projectRole)
                    && workGroup.equals(gpmProjectTeamEntity2.getWorkgroup())
                    && appointmentType.equals(gpmProjectTeamEntity2.getAppointmenttype())
                    && projectRole.equals(gpmProjectTeamEntity2.getProjectrole())
                    && !id.equals(ConvertUtil.convertToString(gpmProjectTeamEntity2.getId()))) {
                throw new ServiceException("项目组中只能有一个组长！");
            }
        }
    }
}
